package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.HuanXinMessageType;
import com.tanhua.dubbo.pojo.Question;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TanHuaService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private QuestionApi questionApi;

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @DubboReference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @DubboReference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Value("${tanhua.default.recommend.users}")
    private String defaultRecommendUsers;

    @Autowired
    private IMService imService;

    public TodayBest queryUserInfo(Long userId) {
        //根据用户id查询用户的基本信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setId(userInfo.getUserId());
        //得分
        todayBest.setFateValue(Convert.toLong(this.recommendUserApi.queryScore(userId, UserThreadLocal.get())));

        //记录访客
        this.visitorsApi.saveVisitor(userId, UserThreadLocal.get(), "个人主页");

        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionApi.queryQuestion(userId);
        if (null != question) {
            //问题
            return question.getTxt();
        }
        return "你是谁？"; //默认问题
    }

    public void replyQuestion(Long userId, String reply) {
        //{"userId":1,"huanXinId":"HX_1","nickname":"黑马小妹","strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？","reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}

        Long myUserId = UserThreadLocal.get();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", myUserId);
        map.put("huanXinId", "HX_" + myUserId);
        map.put("nickname", this.userInfoApi.queryByUserId(myUserId).getNickName());
        map.put("strangerQuestion", this.queryQuestion(userId));
        map.put("reply", reply);

        String msg = JSONUtil.toJsonStr(map);
        //发送消息
        this.huanXinApi.sendMsgFromAdmin("HX_" + userId, HuanXinMessageType.TXT, msg);
    }

    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //查询自己的位置
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(UserThreadLocal.get());

        //根据自己的位置查询
        PageInfo<UserLocationVo> pageInfo = this.userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance),
                1, 100
        );

        List<UserLocationVo> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return Collections.emptyList();
        }

        //TODO 查询用户时，需要考虑到性别的条件，我不考虑性别，在实战中自己完成
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<NearUserVo> result = new ArrayList<>();
        for (UserLocationVo record : records) {
            //排除自己
            if (ObjectUtil.equal(record.getUserId(), UserThreadLocal.get())) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(userInfo.getUserId(), record.getUserId())) {
                    NearUserVo nearUserVo = BeanUtil.toBeanIgnoreError(userInfo, NearUserVo.class);
                    result.add(nearUserVo);
                    break;
                }
            }
        }

        return result;
    }

    public List<TodayBest> queryCardsList() {
        Long userId = UserThreadLocal.get();
        List<RecommendUser> recommendUserList = this.recommendUserApi.queryCardList(userId, 50);
        if (CollUtil.isEmpty(recommendUserList)) {
            //默认推荐 TODO nacos
            List<String> userIdList = StrUtil.split(defaultRecommendUsers, ',');
            recommendUserList = new ArrayList<>();

            for (String uid : userIdList) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(userId);
                recommendUser.setUserId(Convert.toLong(uid));
                // 随机得分
                recommendUser.setScore(RandomUtil.randomDouble(80, 99));
                recommendUserList.add(recommendUser);
            }
        }

        //随机从列表中拿去10个数据进行返回操作
        //方法一：列表不变，随机从中拿去10个数据
        //方法二：只获取前10个数据，但是将列表中的数据顺序打乱 (采用)
        Collections.shuffle(recommendUserList);
        List<RecommendUser> subRecommendUserList = CollUtil.sub(recommendUserList, 0, 10);

        List<Object> userIdList = CollUtil.getFieldValues(subRecommendUserList, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<TodayBest> result = new ArrayList<>();
        for (RecommendUser recommendUser : subRecommendUserList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(userInfo.getUserId(), recommendUser.getUserId())) {
                    TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
                    todayBest.setGender(userInfo.getSex().name().toLowerCase());
                    todayBest.setId(userInfo.getUserId());
                    //得分
                    todayBest.setFateValue(recommendUser.getScore().longValue());
                    result.add(todayBest);
                    break;
                }
            }
        }

        return result;
    }

    public void likeUser(Long likeUserId) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.userLikeApi.likeUser(userId, likeUserId);
        if (result) {
            //判断是否是相互喜欢，如果是，就需要加为好友
            if(this.userLikeApi.isMutualLike(userId, likeUserId)){
                this.imService.contactUser(likeUserId);
            }
        }
    }

    public void notLikeUser(Long likeUserId) {
        Long userId = UserThreadLocal.get();
        this.userLikeApi.notLikeUser(userId, likeUserId);
    }
}
